using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;

namespace Tayninh2011
{
    public partial class FrmConnection : Form
    {
        private IWorkspaceEdit _sdeWorkspace;
        private string _sdeEnvironment;//environment phuc vu geoprocessing
        private bool _connecting;
        FrmMain frmMain = FrmMain.frmMain;
        

        public string SdeEnvironment
        {
            get { return _sdeEnvironment; }
            set { _sdeEnvironment = value; }
        }
        private GeoProcessor _geoProcessor = new GeoProcessor();
        public IWorkspaceEdit SdeWorkspace
        {
            get { return _sdeWorkspace; }
            //set { hWorkspace = value; }
        }
        private string _strConnectionStatus="";
        private string _strDatabase = "";

        public string StrDatabase
        {
            get { return _strDatabase; }
            set { _strDatabase = value; }
        }

        public string StrConnectionStatus
        {
            get { return _strConnectionStatus; }
            set { _strConnectionStatus = value; }
        }

        public FrmConnection()
        {
            InitializeComponent();
            //this.MdiParent = frmMain;
        }
        private void btnConnectToSQL_Click(object sender, EventArgs e)
        {
            funcOpenConnectionSQL();
        }
        private void btnConnectToSDE_Click(object sender, EventArgs e)
        {
            //funcOpenConnectionSQL();
            string strServer = tbxServer.Text;
            string strInstance = tbxInstance.Text;
            string strDatabase = tbxDatabase.Text;
            string strAuthen= "OSA";
            string strVersion = "dbo.DEFAULT";
            string strUser = tbxUser .Text ;
            string strPass = tbxPassword .Text ;
            //FrmMain frmMain = new FrmMain();
            //frmMain = (FrmMain)this.MdiParent;
            try
            {
                
                if (cmbAuthen.SelectedIndex == 0)
                {
                    strAuthen = "OSA";
                }
                else
                {
                    strAuthen = "SQL";
                }
                if (cmbVersion.SelectedIndex == 0)
                {
                    strVersion = "dbo.DEFAULT";
                }
                else
                {
                    strVersion = "sde.DEFAULT";
                }
                ITnToolsWorkspace wspTool = new TnTools();
                this._sdeWorkspace = wspTool.CreateWorkspaceSDE(strServer, strInstance, strAuthen, strDatabase, strVersion, strUser, strPass);
                //funcOpenConnectionSDE_dbo(strServer, strInstance, strDatabase);
                lblStatus.Text = "ket noi thanh cong";
                this.StrConnectionStatus = "CONNECTION_OK";
                this.SdeEnvironment = "Database Connections/Connection to " + tbxServer.Text + ".sde";
                frmMain.SdeEnvironment = this.SdeEnvironment;
                lblStatus.ForeColor = Color.Green;
                frmMain.SetWorkspace(this._sdeWorkspace);
                _connecting = true;
                //MessageBox.Show(frmMain.SdeEnvironment);

                //IWorkspaceName workspaceName = createConnectionFileFromSDE(strServer, strInstance, strAuthen, strDatabase, strVersion, strUser, strPass);
                //MessageBox.Show(workspaceName.BrowseName);
                //createSDEConnectionFile((IGeoProcessor)_geoProcessor);
            }
            catch (Exception e1)
            {
                lblStatus.Text = "khong ket noi duoc";
                this.StrConnectionStatus = "CONNECTION_ERROR";
                lblStatus.ForeColor = Color.Red;
                MessageBox.Show(e1.ToString());
                //frmMain.SetWorkspace(null);
                _connecting = false;
            }
            finally
            {
                frmMain.StrConnectionStatus = this.StrConnectionStatus;
                frmMain.SetConnectionStatus(this.StrConnectionStatus,true);
                this.StrDatabase = this.tbxDatabase.Text;
                frmMain.SetDatabase(this.StrDatabase);
            }
           
            
            
            //MessageBox.Show(frmMain.StrConnectionStatus);
        }


        public void funcOpenConnectionSQL()
        {
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
            scsb.DataSource = tbxServer.Text;
            scsb.InitialCatalog = tbxDatabase.Text;

            if (cmbAuthen.SelectedIndex == 1)
            {
                scsb.IntegratedSecurity = true;
            }
            else if (cmbAuthen.SelectedIndex == 0)
            {
                scsb.IntegratedSecurity = false;
            }


            SqlConnection connSql = new SqlConnection();
            connSql.ConnectionString = scsb.ToString();
            try
            {
                connSql.Open();
                //throw new Exception();

                lblStatus.Text = "ket noi thanh cong";
                lblStatus.ForeColor = Color.Green;
            }
            catch (Exception e1)
            {
                lblStatus.Text = "khong ket noi duoc";
                lblStatus.ForeColor = Color.Red;
                //MessageBox.Show(e1.ToString());
            }
        }
        public void funcOpenConnectionSDE_dbo(string server, string instance, string database, string authentication)
        {
            IPropertySet iPropertySet = new PropertySetClass();
            iPropertySet.SetProperties("SERVER", server);
            iPropertySet.SetProperties("INSTANCE", instance);
            iPropertySet.SetProperties("DATABASE", database);
            iPropertySet.SetProperties("AUTHENTICATION_MODE", authentication);
            iPropertySet.SetProperties("VERSION", "dbo.DEFAULT");

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
            IWorkspaceFactory iWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            //return iWorkspaceFactory.Open(iPropertySet, 0);
        }
        public void funcOpenConnectionSDE_dbo(string server, string instance, string database)
        {
            IPropertySet iPropertySet = new PropertySetClass();
            iPropertySet.SetProperty("SERVER", "ht-laptop_sqlexpress");
            iPropertySet.SetProperty("INSTANCE", "sde:sqlserver:ht-laptop\\sqlexpress");
            iPropertySet.SetProperty("DATABASE", "tayninh2011");
            iPropertySet.SetProperty("AUTHENTICATION_MODE", "OSA");
            //iPropertySet.SetProperties("USERNAME","HT-LAPTOP\\HT");
            //iPropertySet.SetProperties("PASSWORD", "truonghinh");
            //iPropertySet.SetProperties("SERVICE", "5151");
            iPropertySet.SetProperty("VERSION", "dbo.DEFAULT");

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
            IWorkspaceFactory2 wpf = new SdeWorkspaceFactoryClass();
            wpf.Open(iPropertySet, 0);
            //IWorkspaceFactory iWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            //return wp;
        }
        public IWorkspace workspaceConnectionFromSDE(string server, string
    instance, string authentication_mode, string database, string version,string user,string password)
        {
            IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();
            IPropertySet propertySet = new PropertySetClass();
            propertySet.SetProperty("SERVER", server);
            propertySet.SetProperty("INSTANCE", instance);
            propertySet.SetProperty("DATABASE", database);
            
            propertySet.SetProperty("VERSION", version);
            if (authentication_mode != "OSA" && authentication_mode !="osa")
            {
                propertySet.SetProperty("USER", user);
                propertySet.SetProperty("PASSWORD", password);
            }
            else if (authentication_mode == "OSA" || authentication_mode == "osa")
            {
                propertySet.SetProperty("AUTHENTICATION_MODE", authentication_mode);
            }
            else
            {
                MessageBox.Show("Chua xac dinh duoc Authentication_mode");
            }
            if (version == "sde.DEFAULT")
            {
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
                workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            }
            else if (version == "dbo.DEFAULT")
            {
                propertySet.SetProperty("VERSION", version);
            }
            
            return workspaceFactory.Open(propertySet, 0);
        }
        private IWorkspaceName createConnectionFileFromSDE(string server, string
   instance, string authentication_mode, string database, string version, string user, string password)
        {
            IWorkspaceName workspaceName=new WorkspaceNameClass();
            DirectoryInfo dirInfo = new DirectoryInfo("C:\\tempSDE");
            IWorkspaceFactory2 workspaceFactory = new SdeWorkspaceFactoryClass();
            IPropertySet propertySet = new PropertySetClass();
            propertySet.SetProperty("SERVER", server);
            propertySet.SetProperty("INSTANCE", instance);
            propertySet.SetProperty("DATABASE", database);

            propertySet.SetProperty("VERSION", version);
            if (authentication_mode != "OSA" && authentication_mode != "osa")
            {
                propertySet.SetProperty("USER", user);
                propertySet.SetProperty("PASSWORD", password);
            }
            else if (authentication_mode == "OSA" || authentication_mode == "osa")
            {
                propertySet.SetProperty("AUTHENTICATION_MODE", authentication_mode);
            }
            else
            {
                MessageBox.Show("Chua xac dinh duoc Authentication_mode");
            }
            if (version == "sde.DEFAULT")
            {
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
                workspaceFactory = (IWorkspaceFactory2)Activator.CreateInstance(factoryType);
            }
            else if (version == "dbo.DEFAULT")
            {
                propertySet.SetProperty("VERSION", version);
            }
            if (Directory.Exists("C:\\tempSDE\\") == false)
            {
                
                workspaceName = workspaceFactory.Create("C:\\tempSDE\\", "tayninh2011.sde", propertySet, 0);
            }
            else
            {
                try
                {
                    foreach (FileInfo file in dirInfo.GetFiles())
                    {
                        file.Delete();
                    }
                    workspaceName = workspaceFactory.Create("C:\\tempSDE\\", "tayninh2011.sde", propertySet, 0);
                }
                catch { }
            }
            return workspaceName;
        }

        private void frmConnection_Load(object sender, EventArgs e)
        {
            cmbAuthen.Items.Add("Windows Authentication");
            cmbAuthen.Items.Add("SQL Server Authentication");
            cmbVersion.Items.Add("dbo.DEFAULT");
            cmbVersion.Items.Add("sde.DEFAULT");
            //cmbUser ko su dung chuc nang sort
            cmbAuthen.SelectedIndex = 1;
            cmbVersion.SelectedIndex = 1;

            tbxServer.Text = "ht-laptop";//"ht-laptop_sqlexpress";
            tbxInstance.Text = "5151";// "sde:sqlserver:ht-laptop\\sqlexpress";
            tbxDatabase.Text = "sde";//"tayninh2011";
            tbxUser.Text = "sde";
            tbxPassword.Text = "arcsde";
            btnConnectToSDE.Focus();
        }

        public void cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAuthen.SelectedIndex == 0)
            {
                tbxUser.Enabled = false;
                tbxPassword.Enabled = false;
            }
            else if (cmbAuthen.SelectedIndex == 1)
            {
                tbxUser.Enabled = true;
                tbxPassword.Enabled = true;
            }
        }

        //danh cho arcEngine 10
        private void createSDEConnectionFile(IGeoProcessor gp)
        {
            IGeoProcessorResult result = null;
            IVariantArray param = new VarArrayClass();
            param.Add(@"C:\temp"); //thu muc chua file
            param.Add("tayninh.sde"); //ten file
            param.Add("ht-laptop");//server name
            param.Add("5151");//instance
            param.Add("sde");//database
            param.Add("true");//authentication
            param.Add("sde");//user
            param.Add("arcsde");//pass
            param.Add("true");//save user an pass
            param.Add("sde.DEFAULT");//version
            try
            {
                result = (IGeoProcessorResult)gp.Execute("CreateArcSDEConnectionFile_management", param, null);
                string conn_file = result.GetOutput(0).GetAsText();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }
        


        private void btnShowMap_Click(object sender, EventArgs e)
        {
            //FrmMapContainer frmHMapContainer = new FrmMapContainer();
            //frmHMapContainer.Show();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (this._connecting == true)
            {
                this.Close();
                frmMain.Enabled = true;
            }
            else
            {
                Application.Exit();
            }

        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void submnThoat_Click(object sender, EventArgs e)
        {

        }

        private void subMnDangnhap_Click(object sender, EventArgs e)
        {

        }

        private void subMnTuychinhKetnoi_Click(object sender, EventArgs e)
        {

        }
    }
}